//app.js
import mqtt from './static/js/mqtt.min.js'
const util = require('./utils/util.js');
const constant = require('./utils/constant.js');
var eventBus = require('./utils/eventbus.js')
App({
  data: {
    service_uuid: "0000FFFF-0000-1000-8000-00805F9B34FB",
    characteristic_write_uuid: "0000FF01-0000-1000-8000-00805F9B34FB",
    characteristic_read_uuid: "0000FF02-0000-1000-8000-00805F9B34FB",
    name: "BLUFI",
    md5Key: "",
    isInit: 1,
    rssi: -120,
    ip: "",
    port: "",
  },
  connectNum: 0,
  onLaunch: function () {
    wx.removeStorageSync('deviceList');
    // this.getUserInfo();
    
  },
  listen() {
    var self = this
    let options = {
      connectTimeout: 4000, // 超时时间
      // 认证信息 按自己需求填写
      clientId: String((new Date()).getTime()),
      username: 'xxx',
      password: 'xxx',
    }
    this.client = mqtt.connect('wx://temp.api.siruish.cn:8084', options)
    this.client.on('connect', (e) => {
      console.log('成功连接服务器111')
      self.globalData.bus.emit('connect')
    })
    this.client.on('reconnect', function () {
      console.log("发生重新连接！");
      if (self.connectNum >= 1) {
        util.showToast('服务器异常，设备监听重接失败')
        self.client.end()
      } else {
        self.connectNum += 1
      }

    });
    this.client.on('error', (error) => {
      console.log('连接失败:', error)
      util.showToast('服务器异常，设备监听连接失败')
    })
    this.client.on('message', function (topic, message, packet) {
      // message is Buffer
      let mess = message.toString()
      let message1 = JSON.stringify(mess)
      var msg = JSON.parse(JSON.parse(message1))
      console.log(msg, 333);
      let list = wx.getStorageSync(constant.DEVICE_LIST)
      // console.log(list);

      if (!list) {
        list = []
      }
      let index = list.findIndex(item => {
        return item.mac == msg.MAC
      })
      if (topic.includes('will')) {
        if (index !== -1) {
          list[index].status = 0
          util.setStorage(constant.DEVICE_LIST, list);
          self.globalData.bus.emit('refresh')
        }
      } else {
        if (index !== -1) {
          list[index].NAME = msg.name
          list[index].Temp_set = msg.Temp_set
          list[index].Mode_fan = msg.Mode_fan
          list[index].Mode_heat = msg.Mode_heat
          list[index].Temp_real = msg.Temp_real
          list[index].Runningif = msg.Runningif
          list[index].status = msg.Status
          util.setStorage(constant.DEVICE_LIST, list);
          self.globalData.bus.emit('refresh')
        } else {
          list.push(msg)
          util.setStorage(constant.DEVICE_LIST, list);
          self.globalData.bus.emit('refresh')
        }
      }
      // app.client.end()
    })
  },
  client: null,
  onShow() {
    this.listen()

  },
  onHide() {
    this.client.end()
  },
  getUserInfo: function () {
    const self = this;
    wx.getUserInfo({
      success(res) {
        console.log(res);
        self.globalData.userInfo = res.userInfo;
      }
    })
  },

  globalData: {
    userInfo: null,
    udp: "",
    bus: eventBus.eventBus
  }
})